package com.alibaba.chaosblade.box.common.infrastructure.error;

import com.alibaba.chaosblade.box.common.common.domain.ChaosError;
import com.alibaba.chaosblade.box.common.common.enums.CommonErrorCode;
import org.springframework.core.annotation.Order;
import org.springframework.dao.DataIntegrityViolationException;
import org.springframework.stereotype.Component;

/**
 * @author haibin
 */
@Component
@Order(value = 2000)
public class DataBaseThrowableChaosErrorWrapper implements ThrowableChaosErrorWrapper {

    @Override
    public ChaosError wrapper(Throwable throwable) {
        if (throwable instanceof DataIntegrityViolationException) {
            DataIntegrityViolationException dataIntegrityViolationException
                    = (DataIntegrityViolationException) throwable;
            Throwable cause = dataIntegrityViolationException.getCause();
            if (cause == null) {
                return new ChaosError(CommonErrorCode.S_DATA_VIOLATION);
            }
            if (isInstanceOf(cause, "com.mysql.cj.jdbc.MysqlDataTruncation")) {
                return new ChaosError(CommonErrorCode.S_DATA_TRUNCATION, cause.getMessage());
            }
        }
        if (isInstanceOf(throwable, "com.mysql.cj.jdbc.exceptions.SQLError")) {
            return new ChaosError(CommonErrorCode.S_DATA_FIELD_MISSING, throwable.getMessage());
        }
        return null;
    }


    private boolean isInstanceOf(Throwable throwable, String className) {
        try {
            Class<?> clazz = Class.forName(className);
            return clazz.isInstance(throwable);
        } catch (ClassNotFoundException e) {
            return false;
        }
    }
}
